import React, { useState, useEffect, useReducer } from 'react'
import axios from 'axios'

const dataFetchReducer = (state, action) => {
    switch (action.type) {
        case 'FETCH_INIT':
            return { ...state, isLoading: true, isError: false }
        case 'FETCH_SCUESS':
            return { ...state, isError: false, isLoading: false, data: action.payload }
        case 'FETCH_FAILURE':
            return { ...state, isLoading: false, isError: true }
        default:
            throw new error();
    }
}

const useDataApi = (initialUrl, initialData) => {
    const [state, dispatch] = useReducer(dataFetchReducer, {
        data: initialData,
        isLoading: false,
        isError: false
    })
    const { data, isLoading, isError } = state

    const [url, setUrl] = useState(initialUrl)
    useEffect(() => {
        const fetchData = async () => {
            dispatch({ type: 'FETCH_INIT' })
            try {
                const ret = await axios(url)
                dispatch({ type: 'FETCH_SCUESS', payload: ret.data.data })
            } catch (e) {
                dispatch({ type: 'FETCH_FAILURE' })
            }
        }
        fetchData()
    }, [url])
    return [state, setUrl]
}
export default function () {

    const [query, setQuery] = useState('')
    const commonUrl = 'http://wthrcdn.etouch.cn/weather_mini?city='
    const [{ data, isLoading, isError }, doFetch] = useDataApi(commonUrl + '青岛', null)
    return (
        <div>
            <h2>使用reducer</h2>
            <p>输入内容后可直接按回车</p>
            <form onSubmit={(e) => {
                e.preventDefault()
                doFetch(commonUrl + query)
            }}>
                <input value={query} onChange={e => setQuery(e.target.value)} />
                <button type='submit'>搜索</button>
            </form>

            {isError && <div style={{ background: 'pink', padding: '1rem', margin: '1rem' }}>出错啦~~</div>}

            {data && (isLoading
                ? <div> loading...</div>
                : <>
                    <p><strong>城市：</strong>{data.city}</p>
                    <p><strong>当前温度：</strong>{data.wendu}℃</p>
                    <p><strong>感冒预警：</strong>{data.ganmao}</p>
                    <h4>未来{data.forecast?.length}天天气情况</h4>
                    <ul>
                        {data.forecast?.length
                            ? data.forecast.map(item => <li key={item.date}>{`${item.date} - ${item.type} - ${item.low}~${item.high}`}</li>)
                            : null}
                    </ul>
                </>)}

        </div>
    )
}
